import { router } from "./router";
import store from "./store";

const whiteList = [
  "/pages/index/index",
  "/pages/login/login",
  "/pages/register/register",
]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // determine whether the user has logged in
  const hasToken = store.getters.access_token;
  if (hasToken) {
    if (to.path === "/pages/login/login") {
      // if is logged in, redirect to the home page
      next({ path: "/pages/index/index" });
    } else {
      // set the replace: true, so the navigation will not leave a history record
      const hasUserInfo = store.getters.userInfo;
      if (hasUserInfo) {
        next();
      } else {
        try {
          // get user info
          await store.dispatch("GetUserInfo");
          next();
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("RemoveToken");
          next({ path: `/pages/login/login?redirect=${to.path}` });
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next({ path: `/pages/login/login?redirect=${to.path}` });
    }
  }
});
